package com.buwei.infrastructure.response;

import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.View;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class DownloadResponse implements View {

	private final String filename;

	private String contentType = "";

	private final byte[] contents;

	public DownloadResponse(String filename, byte[] contents) {
		this.filename = filename;
		this.contents = contents;
	}

	public DownloadResponse(String filename, String contentType, byte[] contents) {
		this.filename = filename;
		this.contentType = contentType;
		this.contents = contents;
	}

	@Override
	public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 大体的原因就是header中只支持ASCII，所以我们传输的文件名必须是ASCII，当文件名为中文时，必须要将该中文转换成ASCII。 
		response.setHeader("Content-Disposition", "attachment; filename=" + new String(this.filename.getBytes("utf-8"), "iso-8859-1"));
		response.setContentType("application/octet-stream");
		ServletOutputStream stream = response.getOutputStream();
		stream.write(this.contents);
	}

}
